package dao

import (
	"context"
	"sale-admin/internal/dal"
	"sale-admin/internal/models"
	"strings"

	"192.168.1.75/go-pkg/errorx"
	"github.com/golang-module/carbon/v2"
	"gorm.io/gen/field"
	"gorm.io/gorm"
)

type Robot struct{}

// 根据地区查机器
func (Robot) GetSalesIDByAreas3(ctx context.Context, db *gorm.DB, areas3 []string) (salesID []string) {
	m := dal.Use(db).MaRobot
	m.WithContext(ctx).
		Where(m.Deleted.Eq(0)).
		Where(field.NewString(m.TableName(), m.Areas3.ColumnName().String()).In(areas3...)).
		Pluck(m.SalesID, &salesID)
	return
}

// 获取机器列表
func (Robot) RobotList(ctx context.Context, db *gorm.DB, merchantID string, AddTime string, robotName, salesID,
	areas1, areas2, areas3, areas5 string) (data []*models.MaRobot, count int64, err error) {
	m := dal.Use(db).MaRobot
	tx := m.WithContext(ctx).
		Where(m.Deleted.Eq(0)).
		Where(m.RobotType.In([]string{"5", "11"}...))
	if merchantID != "" {
		tx = tx.Where(m.MerchantID.In(strings.Split(merchantID, ",")...))
	}
	if AddTime != "" {
		tx = tx.Where(m.AddTime.Lte(carbon.Parse(AddTime).EndOfDay().ToStdTime()))
	}
	if robotName != "" {
		tx = tx.Where(m.RobotName.In(strings.Split(robotName, ",")...))
	}
	if salesID != "" {
		tx = tx.Where(m.SalesID.In(strings.Split(salesID, ",")...))
	}
	if areas1 != "" {
		tx = tx.Where(field.NewString(m.TableName(), "areas1").In(strings.Split(areas1, ",")...))
	}
	if areas2 != "" {
		tx = tx.Where(field.NewString(m.TableName(), "areas2").In(strings.Split(areas2, ",")...))
	}
	if areas3 != "" {
		tx = tx.Where(field.NewString(m.TableName(), "areas3").In(strings.Split(areas3, ",")...))
	}
	if areas5 != "" {
		tx = tx.Where(field.NewString(m.TableName(), "areas5").In(strings.Split(areas5, ",")...))
	}
	data, err = tx.Find()
	return data, int64(len(data)), err
}

// Detail 设备详情
func (Robot) Detail(ctx context.Context, query *dal.Query, robotID, salesID string) (data *models.MaRobot, err error) {
	if robotID == "" && salesID == "" {
		return nil, errorx.New("无效的设备", -1)
	}
	m := query.MaRobot
	tx := m.WithContext(ctx).
		Where(m.Deleted.Eq(0))
	if robotID != "" {
		tx = tx.Where(m.RobotName.Eq(robotID))
	}
	if salesID != "" {
		tx = tx.Where(m.SalesID.Eq(salesID))
	}
	return tx.Take()
}

// 获取机器详情
func (Robot) RobotDetail(ctx context.Context, db *gorm.DB, merchantID, robotName, salesID string) (data *models.MaRobot, err error) {
	m := dal.Use(db).MaRobot
	tx := m.WithContext(ctx).
		Where(m.Deleted.Eq(0))
	if merchantID != "" {
		tx = tx.Where(m.MerchantID.Eq(merchantID))
	}
	if robotName != "" {
		tx = tx.Where(m.RobotName.Eq(robotName))
	}
	if salesID != "" {
		tx = tx.Where(m.SalesID.Eq(salesID))
	}
	data, err = tx.Take()
	return
}
